from torch import nn
import math
import torch.utils.model_zoo as model_zoo
import torch
import torch.nn.functional as F
from copy import deepcopy
from other_layers import *
from functools import partial
from other_layers import IncepText
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152', 'resnet50_cat', 'resnet50_split_layer4_2',
           'resnet50_split_layer4_1','resnet50_split_layer4','resnet50_cat2',
           'resnet50_SPP', 'resnet50_CS', 'resnet50_CSE','resnet50_cat_dilate']

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


def conv3x3(in_planes, out_planes, stride=1):
    "3x3 convolution with padding"
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000):
        self.inplanes = 64
        super(ResNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)  # 1/16
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)  # 1/32
        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)

        x = self.layer3(x)

        x = self.layer4(x)
        print x.size()

        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x

def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
    return model


def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
    return model


def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
    return model


def resnet101(pretrained=False, **kwargs):
    """Constructs a ResNet-101 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
    return model


def resnet152(pretrained=False, **kwargs):
    """Constructs a ResNet-152 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
    return model





class resnet50_split_layer4(nn.Module):
    def __init__(self, num_classes, pretrained=True):
        super(resnet50_split_layer4, self).__init__()
        self.num_splits = len(num_classes)
        base_model = resnet50(pretrained=pretrained)

        self.conv1 = deepcopy(base_model.conv1)
        self.bn1 = deepcopy(base_model.bn1)
        self.relu = deepcopy(base_model.relu)
        self.maxpool = deepcopy(base_model.maxpool)


        self.layer1 = deepcopy(base_model.layer1)
        self.layer2 = deepcopy(base_model.layer2)
        self.layer3 = deepcopy(base_model.layer3)


        for i in range(self.num_splits):
            self.add_module('layer4_split%d'%i, deepcopy(base_model.layer4))
            self.add_module('fc_split%d'%i, nn.Linear(2048, num_classes[i]))

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)


    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)

        x_cat = []
        for i in range(self.num_splits):
            x_split = getattr(self, 'layer4_split%d' % i)(x)
            x_split = self.avgpool(x_split)
            x_split = x_split.view(x_split.size(0), -1)
            x_split = getattr(self, 'fc_split%d'%i)(x_split)
            x_cat.append(F.softmax(x_split))

        return torch.cat(x_cat,1)



class resnet50_split_layer4_1(nn.Module):
    def __init__(self, num_classes, pretrained=True):
        super(resnet50_split_layer4_1, self).__init__()
        self.num_splits = len(num_classes)
        base_model = resnet50(pretrained=pretrained)

        self.conv1 = deepcopy(base_model.conv1)
        self.bn1 = deepcopy(base_model.bn1)
        self.relu = deepcopy(base_model.relu)
        self.maxpool = deepcopy(base_model.maxpool)


        self.layer1 = deepcopy(base_model.layer1)
        self.layer2 = deepcopy(base_model.layer2)
        self.layer3 = deepcopy(base_model.layer3)

        self.layer4 = nn.Sequential(*list(base_model.layer4.children())[0:-2])

        for i in range(self.num_splits):
            self.add_module('layer4_1_split%d'%i, deepcopy(base_model.layer4[1]))
            self.add_module('layer4_2_split%d' % i, deepcopy(base_model.layer4[2]))
            self.add_module('fc_split%d'%i, nn.Linear(2048, num_classes[i]))

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)


    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x_cat = []
        for i in range(self.num_splits):
            x_split = getattr(self, 'layer4_1_split%d' % i)(x)
            x_split = getattr(self, 'layer4_2_split%d'%i)(x_split)
            x_split = self.avgpool(x_split)
            x_split = x_split.view(x_split.size(0), -1)
            x_split = getattr(self, 'fc_split%d'%i)(x_split)
            x_cat.append(F.softmax(x_split))

        return torch.cat(x_cat,1)



class resnet50_split_layer4_2(nn.Module):
    def __init__(self, num_classes, pretrained=True):
        super(resnet50_split_layer4_2, self).__init__()
        self.num_splits = len(num_classes)
        base_model = resnet50(pretrained=pretrained)

        self.conv1 = deepcopy(base_model.conv1)
        self.bn1 = deepcopy(base_model.bn1)
        self.relu = deepcopy(base_model.relu)
        self.maxpool = deepcopy(base_model.maxpool)


        self.layer1 = deepcopy(base_model.layer1)
        self.layer2 = deepcopy(base_model.layer2)
        self.layer3 = deepcopy(base_model.layer3)

        self.layer4 = nn.Sequential(*list(base_model.layer4.children())[0:-1])

        for i in range(self.num_splits):
            self.add_module('layer4_2_split%d'%i, deepcopy(base_model.layer4[2]))
            self.add_module('fc_split%d'%i, nn.Linear(2048, num_classes[i]))

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)


    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x_cat = []
        for i in range(self.num_splits):
            x_split = getattr(self, 'layer4_2_split%d'%i)(x)
            x_split = self.avgpool(x_split)
            x_split = x_split.view(x_split.size(0), -1)
            x_split = getattr(self, 'fc_split%d'%i)(x_split)
            x_cat.append(F.softmax(x_split))

        return torch.cat(x_cat,1)

class CS_Resnet(nn.Module):
    def __init__(self, base1, base2):
        super(CS_Resnet, self).__init__()
        self.base1 = deepcopy(base1)
        self.base2 = deepcopy(base2)

        self.cs_maxpool = CrossStitch(in_channels=64, mode='channel_wise')
        self.cs_layer1 = CrossStitch(in_channels=256, mode='channel_wise')
        self.cs_layer2 = CrossStitch(in_channels=512, mode='channel_wise')
        self.cs_layer3 = CrossStitch(in_channels=1024, mode='channel_wise')
        self.cs_layer4 = CrossStitch(in_channels=2048, mode='channel_wise')
        self.cs_avgpool = CrossStitch(in_channels=2048, mode='channel_wise')

    def forward(self, x):
        xa = self.base1.conv1(x)
        xa = self.base1.bn1(xa)
        xa = self.base1.relu(xa)
        xa = self.base1.maxpool(xa)

        xb = self.base2.conv1(x)
        xb = self.base2.bn1(xb)
        xb = self.base2.relu(xb)
        xb = self.base2.maxpool(xb)

        xa,xb = self.cs_maxpool(xa,xb)

        xa = self.base1.layer1(xa)
        xb = self.base2.layer1(xb)
        xa,xb = self.cs_layer1(xa,xb)

        xa = self.base1.layer2(xa)
        xb =  self.base2.layer2(xb)
        xa,xb = self.cs_layer2(xa,xb)

        xa = self.base1.layer3(xa)
        xb = self.base2.layer3(xb)
        xa,xb = self.cs_layer3(xa,xb)

        xa = self.base1.layer4(xa)
        xb = self.base2.layer4(xb)
        xa,xb = self.cs_layer4(xa,xb)

        xa = self.base1.avgpool(xa)
        xb = self.base2.avgpool(xb)
        xa,xb = self.cs_avgpool(xa,xb)

        xa = xa.view(xa.size(0),-1)
        xb = xa.view(xb.size(0), -1)

        xa = self.base1.fc(xa)
        xb = self.base2.fc(xb)

        return torch.cat([xa,xb], 1)


class CSE_Resnet(nn.Module):
    def __init__(self, base1, base2):
        '''
        cross SE
        '''
        super(CSE_Resnet, self).__init__()
        self.base1 = deepcopy(base1)
        self.base2 = deepcopy(base2)

        self.cse_layer1a = CrossSELayer(channel=256,reduction=16)
        self.cse_layer1b = CrossSELayer(channel=256, reduction=16)
        self.cse_layer2a = CrossSELayer(channel=512,reduction=16)
        self.cse_layer2b = CrossSELayer(channel=512, reduction=16)
        self.cse_layer3a = CrossSELayer(channel=1024,reduction=16)
        self.cse_layer3b = CrossSELayer(channel=1024, reduction=16)
        self.cse_layer4a = CrossSELayer(channel=2048,reduction=16)
        self.cse_layer4b = CrossSELayer(channel=2048, reduction=16)

    def forward(self, x):
        xa = self.base1.conv1(x)
        xa = self.base1.bn1(xa)
        xa = self.base1.relu(xa)
        xa = self.base1.maxpool(xa)

        xb = self.base2.conv1(x)
        xb = self.base2.bn1(xb)
        xb = self.base2.relu(xb)
        xb = self.base2.maxpool(xb)


        xa_ = self.base1.layer1(xa)
        xb_ = self.base2.layer1(xb)
        xa = self.cse_layer1a(xb_,xa_)
        xb = self.cse_layer1b(xa_, xb_)

        xa_ = self.base1.layer2(xa)
        xb_ =  self.base2.layer2(xb)
        xa = self.cse_layer2a(xb_,xa_)
        xb = self.cse_layer2b(xa_, xb_)

        xa_ = self.base1.layer3(xa)
        xb_ = self.base2.layer3(xb)
        xa = self.cse_layer3a(xb_,xa_)
        xb = self.cse_layer3b(xa_, xb_)

        xa_ = self.base1.layer4(xa)
        xb_ = self.base2.layer4(xb)
        xa = self.cse_layer4a(xb_,xa_)
        xb = self.cse_layer4b(xa_, xb_)


        xa = self.base1.avgpool(xa)
        xb = self.base2.avgpool(xb)

        xa = xa.view(xa.size(0),-1)
        xb = xa.view(xb.size(0), -1)

        xa = self.base1.fc(xa)
        xb = self.base2.fc(xb)

        return torch.cat([xa,xb], 1)

def resnet50_cat( num_classes, pretrained=True):
    base_model = resnet50(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    return base_model

def resnet101_cat( num_classes, pretrained=True):
    base_model = resnet101(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    return base_model

def resnet152_cat( num_classes, pretrained=True):
    base_model = resnet152(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    return base_model


def resnet50_cat2( num_emd, num_classes, pretrained=True):
    base_model = resnet50(pretrained=pretrained)
    base_model.fc = cat_linear2(2048,num_emd, num_classes)
    return base_model


def resnet50_SPP(num_classes, out_sizes=(4,3,2,1) ,pretrained=True):
    base_model = resnet50(pretrained=pretrained)
    base_model.avgpool = SPP_layer(out_sizes=out_sizes,pooling='avg')
    total_in = 0
    for i in out_sizes:
        total_in += i ** 2
    base_model.fc = cat_linear(2048*total_in, num_classes)
    return base_model


def resnet50_CS(num_classes, pretrained=True, **kwargs):
    if 'base1' in kwargs:
        assert kwargs['base1'].fc.out_features_list[0] == num_classes[0]
        base1 = kwargs['base1']
    else:
        base1 = resnet50(pretrained=pretrained)
        base1.fc = cat_linear(in_features=2048, out_features_list=[num_classes[0]])

    if 'base2' in kwargs:
        assert kwargs['base2'].fc.out_features_list[0] == num_classes[1]
        base2 = kwargs['base2']
    else:
        base2 = resnet50(pretrained=pretrained)
        base2.fc = cat_linear(in_features=2048, out_features_list=[num_classes[1]])

    return CS_Resnet(base1,base2)

def resnet50_CSE(num_classes, pretrained=True, **kwargs):
    if 'base1' in kwargs:
        assert kwargs['base1'].fc.out_features_list[0] == num_classes[0]
        base1 = kwargs['base1']
    else:
        base1 = resnet50(pretrained=pretrained)
        base1.fc = cat_linear(in_features=2048, out_features_list=[num_classes[0]])

    if 'base2' in kwargs:
        assert kwargs['base2'].fc.out_features_list[0] == num_classes[1]
        base2 = kwargs['base2']
    else:
        base2 = resnet50(pretrained=pretrained)
        base2.fc = cat_linear(in_features=2048, out_features_list=[num_classes[1]])

    return CSE_Resnet(base1,base2)


def resnet50_cat_dilate( num_classes, pretrained=True):
    base_model = resnet50(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    base_model.layer3.apply(partial(_nostride_dilate, dilate=2))
    base_model.layer4.apply(partial(_nostride_dilate, dilate=4))
    return base_model

def resnet101_cat_dilate( num_classes, pretrained=True):
    base_model = resnet101(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    base_model.layer3.apply(partial(_nostride_dilate, dilate=2))
    base_model.layer4.apply(partial(_nostride_dilate, dilate=4))
    return base_model

def resnet101_cat_dilate2( num_classes, pretrained=True):
    base_model = resnet101(pretrained=pretrained)
    base_model.fc = cat_linear(2048, num_classes)
    base_model.layer2.apply(partial(_nostride_dilate, dilate=2))
    base_model.layer3.apply(partial(_nostride_dilate, dilate=4))
    base_model.layer4.apply(partial(_nostride_dilate, dilate=8))
    return base_model

class Res101_IncepText(nn.Module):
    '''
    0.9818
    '''

    def __init__(self, num_classes, pretrained=True):
        super(Res101_IncepText, self).__init__()
        base_model = resnet101(pretrained=pretrained)
        self.inplanes = 64
        self.conv1 = base_model.conv1
        self.bn1 = base_model.bn1
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = base_model.layer1
        self.layer2 = base_model.layer2
        self.layer3 = base_model.layer3  # 1/16
        self.layer4 = base_model.layer4  # 1/32

        self.incept = IncepText(in_channels=2048,out_channels=1024)

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)

        self.fc = cat_linear(in_features=1024, out_features_list=num_classes)


    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.incept(x)

        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x


class Resnet50_merge34(nn.Module):
    '''
    0.9818
    '''

    def __init__(self, num_classes, pretrained=True):
        super(Resnet50_merge34, self).__init__()
        base_model = resnet50(pretrained=pretrained)
        self.inplanes = 64
        self.conv1 = base_model.conv1
        self.bn1 = base_model.bn1
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = base_model.layer1
        self.layer2 = base_model.layer2
        self.layer3 = base_model.layer3  # 1/16
        self.layer4 = base_model.layer4  # 1/32

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)

        self.fc = cat_linear(in_features=2048 + 1024, out_features_list=num_classes)

        self.layer3.apply(partial(_nostride_dilate, dilate=2))
        self.layer4.apply(partial(_nostride_dilate, dilate=4))

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        l3 = self.layer3(x)
        l4 = self.layer4(l3)
        dl4 = F.upsample(l4, size=l3.size()[2:], mode='bilinear')
        x = torch.cat([dl4, l3], dim=1)

        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x


class Resnet101_merge34(nn.Module):

    def __init__(self, num_classes, pretrained=True):
        super(Resnet101_merge34, self).__init__()
        base_model = resnet101(pretrained=pretrained)
        self.inplanes = 64
        self.conv1 = base_model.conv1
        self.bn1 = base_model.bn1
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = base_model.layer1
        self.layer2 = base_model.layer2
        self.layer3 = base_model.layer3  # 1/16
        self.layer4 = base_model.layer4  # 1/32

        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)

        self.fc = cat_linear(in_features=2048 + 1024, out_features_list=num_classes)
        self.layer3.apply(partial(_nostride_dilate, dilate=2))
        self.layer4.apply(partial(_nostride_dilate, dilate=4))

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        l3 = self.layer3(x)
        l4 = self.layer4(l3)
        x = torch.cat([l4, l3], dim=1)

        x = self.avgpool(x)

        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x



class Resnet101_newtest(nn.Module):

    def __init__(self, num_classes, pretrained=True):
        super(Resnet101_newtest, self).__init__()
        base_model = resnet101(pretrained=pretrained)
        self.inplanes = 64
        self.conv1 = base_model.conv1
        self.bn1 = base_model.bn1
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = base_model.layer1
        self.layer2 = base_model.layer2
        self.layer3 = base_model.layer3  # 1/16
        self.layer4 = base_model.layer4  # 1/32

        self.FcMap = cat_FcMap(in_features=2048, out_features_list=num_classes, bias=True)
        self.MapConv = nn.Sequential(
            nn.Conv2d(sum(num_classes), sum(num_classes),kernel_size=1),
            nn.BatchNorm2d(sum(num_classes)),
            nn.ReLU(inplace=True)
        )
        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)

        self.fc = cat_linear(in_features=sum(num_classes), out_features_list=num_classes)

        for m in self.MapConv.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
        # self.layer3.apply(partial(_nostride_dilate, dilate=2))
        # self.layer4.apply(partial(_nostride_dilate, dilate=4))

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        logps_cat, fmaps_cat = self.FcMap(x)

        x = self.MapConv(fmaps_cat)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return logps_cat, x


class Resnet101_newtest2(nn.Module):

    def __init__(self, num_classes, pretrained=True):
        super(Resnet101_newtest2, self).__init__()
        base_model = resnet101(pretrained=pretrained)
        self.inplanes = 64
        self.conv1 = base_model.conv1
        self.bn1 = base_model.bn1
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = base_model.layer1
        self.layer2 = base_model.layer2
        self.layer3 = base_model.layer3  # 1/16
        self.layer4 = base_model.layer4  # 1/32

        self.FcMap = cat_FcMap(in_features=2048, out_features_list=num_classes, bias=True)
        self.MapConv = nn.Sequential(
            nn.Conv2d(sum(num_classes), sum(num_classes),kernel_size=1),
            nn.BatchNorm2d(sum(num_classes)),
            nn.ReLU(inplace=True)
        )
        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)

        self.fc = cat_linear(in_features=sum(num_classes), out_features_list=num_classes)

        for m in self.MapConv.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
        # self.layer3.apply(partial(_nostride_dilate, dilate=2))
        # self.layer4.apply(partial(_nostride_dilate, dilate=4))

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        logps_cat, fmaps_cat = self.FcMap(x)

        x = self.MapConv(fmaps_cat)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return logps_cat, (x+logps_cat)*0.5

class Resnet101_d_newtest2(nn.Module):

    def __init__(self, num_classes, pretrained=True):
        super(Resnet101_d_newtest2, self).__init__()
        base_model = resnet101(pretrained=pretrained)
        self.inplanes = 64
        self.conv1 = base_model.conv1
        self.bn1 = base_model.bn1
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = base_model.layer1
        self.layer2 = base_model.layer2
        self.layer3 = base_model.layer3  # 1/16
        self.layer4 = base_model.layer4  # 1/32

        self.FcMap = cat_FcMap(in_features=2048, out_features_list=num_classes, bias=True)
        self.MapConv = nn.Sequential(
            nn.Conv2d(sum(num_classes), sum(num_classes),kernel_size=1),
            nn.BatchNorm2d(sum(num_classes)),
            nn.ReLU(inplace=True)
        )
        self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)

        self.fc = cat_linear(in_features=sum(num_classes), out_features_list=num_classes)

        for m in self.MapConv.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
        self.layer3.apply(partial(_nostride_dilate, dilate=2))
        self.layer4.apply(partial(_nostride_dilate, dilate=4))

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        logps_cat, fmaps_cat = self.FcMap(x)

        x = self.MapConv(fmaps_cat)
        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return logps_cat, (x+logps_cat)*0.5


def _nostride_dilate( m, dilate):
    classname = m.__class__.__name__
    if classname=='Conv2d':
        # the convolution with stride
        if m.stride == (2, 2):
            m.stride = (1, 1)
            if m.kernel_size == (3, 3):
                m.dilation = (dilate//2, dilate//2)
                m.padding = (dilate//2, dilate//2)
        # other convoluions
        else:
            if m.kernel_size == (3, 3):
                m.dilation = (dilate, dilate)
                m.padding = (dilate, dilate)

if __name__ == '__main__':
    # model = resnet50()
    # print model
    # # # #
    # x = torch.FloatTensor(3,3,224,224).zero_()
    # x = torch.autograd.Variable(x)
    # # # # import numpy as np
    # # # #
    # # # # attrs = torch.from_numpy(np.array([0,2,1]))
    # # # #
    # y = model(x)
    # print y
    # # #

    model = Resnet101_newtest(num_classes=[10,5])
    print model
    x = torch.FloatTensor(3,3,336,336).zero_()
    x = torch.autograd.Variable(x)
    y = model(x)
    print y[0]
    print y[1]
